import React, { useEffect, useState } from "react";
import { Table, Button, Tooltip, message } from "antd";
import axios from "axios";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";

export default function Audit() {
  const [dataSource, setdataSource] = useState([]);
  useEffect(() => {
    axios.get("/news?_expand=category&auditState=1").then(({ data }) => {
      let list = [];
      const { username, roleId, region } = JSON.parse(
        localStorage.getItem("token")
      );
      const roleObj = {
        1: "superAdmin",
        2: "admin",
        3: "editer"
      };
      if (roleObj[roleId] === "superAdmin") {
        // 超级管理员返回所有用户
        list = data;
      } else if (roleObj[roleId] === "admin") {
        // 区域管理员返回自己和区域编辑用户
        list = [
          ...data.filter(v => v.author === username),
          ...data.filter(
            v => v.region === region && roleObj[v.roleId] === "editer"
          )
        ];
      }
      setdataSource(list);
    });
  }, []);
  const columns = [
    {
      title: "新闻标题",
      dataIndex: "title",
      render(title, item) {
        return <a href={`/#/news-manage/preview/${item.id}`}>{title}</a>;
      }
    },
    {
      title: "作者",
      dataIndex: "author"
    },
    {
      title: "新闻分类",
      dataIndex: "category",
      render(category) {
        return category.title;
      }
    },
    {
      title: "操作",
      render(item) {
        return (
          <div>
            <Tooltip title="通过">
              <Button
                type="primary"
                icon={<CheckOutlined />}
                shape="circle"
                size="large"
                style={{ marginRight: "10px" }}
                onClick={() => {
                  handleAudit(item.id, 2, 1);
                }}
              />
            </Tooltip>
            <Tooltip title="不通过">
              <Button
                type="danger"
                icon={<CloseOutlined />}
                shape="circle"
                size="large"
                onClick={() => {
                  handleAudit(item.id, 3, 0);
                }}
              />
            </Tooltip>
          </div>
        );
      }
    }
  ];
  const handleAudit = (id, auditState, publishState) => {
    axios
      .patch(`/news/${id}`, {
        auditState,
        publishState
      })
      .then(() => {
        setdataSource(dataSource.filter(v => v.id !== id));
        message.success("操作成功！");
      });
  };
  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      pagination={{ pageSize: 5 }}
      rowKey={item => item.id}
    />
  );
}
